package tss.util;

public class VectorTimestampImpl implements VectorTimestamp {

	int[] vector;
	int id;

	/*
	 * Where length is the size of the vector and id is an identity of the
	 * process that owns the vector timestamp. length should be > 0 and id
	 * should be >= 0 and < length
	 */
	public VectorTimestampImpl(int length, int id) // 0
			throws IllegalArgumentException {
		if (length <= 0 || id < 0) // 1
			throw new IllegalArgumentException(); // 2

		vector = new int[length]; // 3
		this.id = id;
	}

	public int id() { // 0
		return id;
	}

	public int get(int id) throws IllegalArgumentException {// 0
		if (id < 0 || id >= size())// 1
			throw new IllegalArgumentException();// 2

		return vector[id];// 3
	}

	public void increment() {// 0
		vector[id]++; // 1
	}

	public void max(VectorTimestamp other) throws IllegalArgumentException { // 0
		if (other.size() != size())// 1
			throw new IllegalArgumentException();// 2

		for (int i = 0; i < size(); i++) {// 3
			if (other.get(i) > vector[i])// 4
				vector[i] = other.get(i);// 5
		}
	}

	public int size() {
		return vector.length;
	}

	public boolean canDeliver(VectorTimestamp other)
			throws IllegalArgumentException {
		// for 0 <= i < size(), i != other.id(), i != id(): other[i] <= this[i],
		// and
		// other[other.id()] == this[other.id()] + 1
		if (size() != other.size()) // 1
			throw new IllegalArgumentException(); // 2

		if (other.get(other.id()) != (vector[other.id()] + 1)) // 3
			return false;// 4
		for (int i = 0; i < size(); i++) {// 5
			if (i != id() && i != other.id() && other.get(i) > vector[i]) // 6
				return false;// 7
		}
		return true;// 8
	}

	public void setArray(int[] vec) {
		vector = vec;
	}
}
